
import mqtt from 'mqtt';

const options = {
    host: "mqtt.aidoor.net",
    port: 1883,
    keepalive: 30,
    connectTimeout: 5000,
    reconnectPeriod: 3000,
    queueQoSZero: false,
    clientId: 'ai_story_' + new Date().getTime(),
}

const mqttClient = mqtt.connect(options);
mqttClient.on('connect', function () {
    console.log(`mqtt 连接成功`);
});
mqttClient.on('error', function (error) {
    console.log('mqtt异常:', error);
    if (!mqttClient.reconnecting) {
        console.log("开始重新连接");
        mqttClient.reconnect(options)
    }
})



/**
 * 
 * @param {话题} topic 
 * @param {发送数据包} payload 
 */
function sendMessage(topic, payload) {
    mqttClient.publish(topic, payload, { qos_level: 0, retain: false }, function (error, packet) {
        if (error) {
            console.log('mqtt 发送消息失败:', error, packet);
        }
    });
}

/**
 * 推送消息给微信公众号
 */
export function sendMessageToDevice(type, deviceId, payload) {
    let json = payload;
    json.type = type;
    const topic = '/ai_story/to_wechat/' + deviceId;
    console.log(`推消息给设备 :${topic},  信息:${JSON.stringify(json)}`)
    sendMessage(topic, JSON.stringify(json));
}